package com.example.gitdemo2;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class SocketClient {
    private Socket socket;
    private InputStream input;
    private OutputStream output;

    private String serverIp;
    private int serverPort;

    public SocketClient(String serverIp, int serverPort) {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    // 连接到服务器
    public void connect(final DataCallback callback) {
        new Thread(() -> {
            try {
                socket = new Socket(serverIp, serverPort);
                input = socket.getInputStream();
                output = socket.getOutputStream();
                callback.connectSuccess(true);
            } catch (Exception e) {
                callback.connectSuccess(false);
                e.printStackTrace();
            }
        }).start();
    }

    // 发送数据
    public void sendData(String data) {
        new Thread(() -> {
            try {
                if (socket != null && output != null) {
                    output.write(data.getBytes());
                    output.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    // 接收数据
    public void receiveData(final DataCallback callback) {
        new Thread(() -> {
            try {
                byte[] bytes = new byte[1024];
                int len;
                StringBuilder sb = new StringBuilder();
                while ((len = input.read(bytes))!=-1) {
                    sb.append(new String(bytes,0,len,"UTF-8"));
                }
                callback.onDataReceived(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    // 数据回调接口
    public interface DataCallback {
        void connectSuccess(boolean result);
        void onDataReceived(String data);
    }

    // 关闭连接
    public void close() {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
